package common.web.action;

import java.lang.reflect.Field;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.web.vo.Result;

/**
 * 
 * 验证的Action
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/validation")
public class ValidationAction extends CommonAction {

	private static final Logger logger = Logger.getLogger(ValidationAction.class);

	/**
	 * entityName 实体名字
	 * field 需要验证的字段
	 * value 字段的值
	 * id 需要排除的ID
	 * 
	 * @param json
	 * @return
	 */
	@RequestMapping("/unique")
	@ResponseBody
	public Result unique(@RequestBody JSONObject json){
		try {
			String entityName = json.getString("entityName");
			String field = json.getString("field");
			Class<?> clazz = Class.forName(entityName);
			Field f = ReflectionUtils.findField(clazz , field);
			Class<?> type = f.getType();
			Object value = json.getObject("value", type);
			String id = json.getString("id");
			if(unique(entityName, field, value, id)) {
				return Result.SUCCESS;
			}
		} catch (ClassNotFoundException e) {
			logger.error("", e);
		}
		return Result.fail("");
	}

}
